<template>
	<view class="container" :style="{ paddingTop: statusBarHeight + 'px' }">
		<uni-section title="奖励信息" type="line">
			<view class="example">
				<!-- 基础表单校验 -->
				<uni-forms ref="valiForm" :rules="rules" :model="valiFormData" labelWidth="160rpx">
					<uni-forms-item label="奖励对象"  name="userIds" size="25" v-model="valiFormData.userIds" class="add-user-class">
				
					<view class="tabs-wrapper">
						<view v-for="(tab, index) in userList" :key="tab.id" class="tab-item">
							<view class="tab-text">
								{{ tab.name }}
							</view>
							<view class="close-btn" @click="closeTab(index,tab.id)">x</view>
						</view>
					</view>
					<uni-icons type="plusempty" color="#5E6D82" size="25" style="background-color: #F0F0F0;" @click="createUser()"></uni-icons>
					
					<tki-tree ref="tkitree" 
							  :range="treeData" 
							  :rangeKey="rangeKey" 
							  :foldAll="true"
							  :multiple="true"
							  :selectParent="false"
							  confirmColor="#4e8af7"
							  @confirm="treeConfirm" 
							  @cancel="treeCancel"/>	
							  
					</uni-forms-item>
					<uni-forms-item label="奖励日期" name="rewardDate">
							<uni-datetime-picker type="date" :clear-icon="false"  return-type="timestamp"  v-model="valiFormData.rewardDate" />
					</uni-forms-item>
					<uni-forms-item label="奖励事项" name="sid">
						<uni-data-picker v-model="valiFormData.sid" :localdata="sidData" @change="onPickerChange" :readonly="isSidReadonly" popup-title="选择奖励事项">
						</uni-data-picker>
					</uni-forms-item>
					<uni-forms-item label="自定义事项"  name="matter">
						<uni-easyinput v-model="valiFormData.matter" placeholder="请输入自定义事项"  @input="onMatterChage" :disabled="isMatterDisabled"/>
					</uni-forms-item>
					<uni-forms-item label="奖励分数"  name="rewardScore">
						<uni-easyinput  v-model="valiFormData.rewardScore" :disabled="isRewardScoreDisabled" placeholder="请输入奖励分数" />
					</uni-forms-item>
					<uni-forms-item label="奖励金额"  name="money">
						<uni-easyinput v-model="valiFormData.money" placeholder="请输入奖励金额" />
					</uni-forms-item>
					<uni-forms-item label="备注">
					</uni-forms-item>
					<view style="padding:0rpx 10rpx">
						<TabEditor ref="tabEditor"  @data-sent="handleEditorSent"/>
					</view>
				</uni-forms>
				<button type="primary"  style="width: 250px;" @click="submit('valiForm')">提交</button>
  
			</view>
		</uni-section>
		
	</view>
</template>

<script>
	import TabEditor from './TabEditor.vue';
	import tkiTree from "@/components/tki-tree/tki-tree.vue"
	export default {
		components: {
		    TabEditor,
			tkiTree
		  },
		data() {
			return {
				statusBarHeight:0,
				eventChannel:"",
				rangeKey:"name",
				treeData:[],
				isSidReadonly:false,
				isMatterDisabled:false,
				isRewardScoreDisabled:false,
				scoreData:[],
				flag:0,
				readOnly: false,
				formats: {},
				userList:[],
				// 基础表单数据
				valiFormData: {
					userIds: [],
					rewardDate: new Date().getTime(),
					note: '',
					sid: '',
					createUserId:'',
					matter: '',
					money: '',
					rewardScore: '',
				},
				// 加减分机制
				sidData: [],
				// 校验规则
				rules: {
					userIds: {
						rules: [{
							format: 'array',
							required: true,
							errorMessage: '奖励对象不能为空'
						}]
					},
					rewardDate: {
						rules: [{
							required: true,
							errorMessage: '奖励日期不能为空'
						}]
					},
					sid: {
						rules: [{
							required: true,
							errorMessage: '奖励事项不能为空'
						}]
					},
					matter: {
						rules: [{
							required: true,
							errorMessage: '自定义奖励事项不能为空'
						}]
					},
					money: {
						rules: [{
							required: false,
							errorMessage: '奖励金额不能为空'
						}, {
							format: 'number',
							errorMessage: '奖励金额只能输入数字'
						}, {
							validateFunction: function(rule, value, data, callback) {
								if (value <= 0) {
									callback('奖励金额必须大于0')
								}
								return true
							}
						}]
					},
					rewardScore: {
						rules: [{
							required: true,
							errorMessage: '奖励分数不能为空'
						}, {
							format: 'number',
							errorMessage: '奖励分数只能输入数字'
						}, {
							validateFunction: function(rule, value, data, callback) {
								if (value <= 0) {
									callback('奖励分数必须大于0')
								}
								return true
							}
						}]
					},
					note: {
						rules: [{
							required: true,
							errorMessage: '奖励分数不能为空'
						}, {
							format: 'number',
							errorMessage: '奖励分数只能输入数字'
						}]
					}
				}
			}
		},
		mounted(){
			// 获取设备信息
			const systemInfo = uni.getSystemInfoSync();
			this.statusBarHeight = systemInfo.statusBarHeight; 
		},
		onLoad(option) {
			const storageData = uni.getStorageSync('userInfo');
			this.valiFormData.createUserId =storageData.userId;
			this.userList=[];
			this.valiFormData.userIds=[];

			//加减分下拉框数据
			this.$myRequest.getRequest("/api/score-level/getScoreLevel", {flag:this.flag}).then(res => {
				this.scoreData = res;
				// 数据预处理
				this.sidData = res.map(item => ({
					value: item.sid,
					text: item.sname,
					rewardScore: item.score,
				}));
			}).catch(res => { 
				uni.showToast({
				  title: '获取加扣分机制失败!',
				  icon: 'none'
				});
			});
			this.$myRequest.getRequest("/api/dept/getDepartmentsWithUsers", {userId:storageData.userId}).then(res => {
				this.treeData=res;
			}).catch(res => { 
				uni.showToast({
				  title: '获取部门和用户失败!',
				  icon: 'none'
				});
			});
		},
		onReady() {
			// 设置自定义表单校验规则，必须在节点渲染完毕后执行
			// this.$refs.customForm.setRules(this.customRules)
		},
		methods: {
			handleEditorSent(data){
				this.valiFormData.note = data.data.html;
			},
			// 确定回调事件
			treeConfirm(e) {
				// 必须选择
				if (e.length == 0) {
					this.userList = [];
					this.valiFormData.userIds=[];
					return;
				}
				this.userList=e;
				e.forEach(user => {
				    this.valiFormData.userIds.push(user.id);
				});
			},
			// 取消回调事件
			treeCancel(e) {

			},
			onMatterChage(e){
				this.$refs.valiForm.clearValidate(['sid'])
				// 判断值是否为空或仅包含空格
				if(e === ''|| e.trim() ===''){
					this.isSidReadonly=false;
					// this.isRewardScoreDisabled=true;
				}else{
					this.isSidReadonly=true;
					// this.isRewardScoreDisabled=false;
				}
			},
			onPickerChange(e) {
				const array = e.detail.value;
				if (!Array.isArray(array) || array.length === 0) {
					this.valiFormData.rewardScore ='';
					this.isRewardScoreDisabled=false;
					this.isMatterDisabled=false;
					return;
				}
				const selectedValue = array[0].value;
				const selectedItem = this.sidData.find(item => item.value === selectedValue);

				this.valiFormData.rewardScore = selectedItem.rewardScore;
				this.isRewardScoreDisabled=true;
				this.isMatterDisabled=true;
				this.$refs.valiForm.clearValidate(['matter'])
			},
			closeTab(index, paramId) {
				// 关闭指定的 tab
				this.userList.splice(index, 1);
				this.valiFormData.userIds.splice(index, 1);

				const newTreeData = [];
				this.treeData.forEach(item=> {
					const newchildrenArray = [];
					 if(Array.isArray(item.children) && item.children.length > 0){
						 item.children.forEach(citem => {
							 if(paramId === citem.id){
							 	citem.checked = false
							 }else if(this.userList.some(u => u.id === citem.id)){
								citem.checked = true; 
							 }
							 newchildrenArray.push(citem);
						 }); 
					 }
					 item.children=newchildrenArray;
					 newTreeData.push(item);
				});
				this.treeData=newTreeData;
				
			},
			createUser(){
				this.$refs.tkitree._show();
			},
			submit(ref) {
				let validArray =['userIds','rewardDate','money','rewardScore'];
				if(!this.isSidReadonly && !this.isMatterDisabled){
					validArray.push('sid');
					validArray.push('matter');
				}
				const $this = this;
				console.log($this.valiFormData)
				this.$refs[ref].validateField(validArray).then(res => {
					// uni.showToast({
					// 	title: `校验通过`
					// })
					uni.showModal({
					  title: '提示',
					  content: '您是否要提交奖励记录?',
					  confirmText: '确定',
					  cancelText: '取消',
					  success(res) {
					    if (res.confirm) {
					      $this.$myRequest.postRequest("/api/rewards/createRewards", $this.valiFormData).then(res => {
					      	if(res.code !=-1){
					      		uni.navigateBack({
					      		    delta: 1 ,
					      			success: function(res) {
					      				console.log('返回上级页面成功');
					      				$this.getOpenerEventChannel().emit('addRewardCallback', {});
					      			},
					      			fail: function() {
					      				console.log('返回上级页面失败');
					      			}
					      		});
					      	}else{
					      		uni.showToast({
					      		  title: '新建失败!',
					      		  icon: 'none'
					      		});
					      		return;
					      	}
					      });
					    } else if (res.cancel) {
					    }
					  }
					});
				}).catch(err => {
					console.log('err', err);
				})
			}
		}
	}
		
</script>

<style scoped>
	.container {
		padding-top: env(safe-area-inset-top); 
	}
	.Treeform {
        display: flex;
        align-items: center;
    }
	 page{
	 	background-color: #ffffff;
	 }
	.add-user-class{
	  display: flex; /* 使用 flex 布局 */
	  justify-content: flex-start; /* 水平方向左对齐 */
	  align-items: center;
	 }
	.tabs-wrapper {
	  display: flex;
	  flex-wrap: wrap;
	  gap: 4rpx; 
	}
	 
	.tab-item {
	  font-size: 22rpx;
	  display:flex;
	  flex-direction: row;
	  align-items: center;
	  background-color: #f0f0f0;
	  border-radius: 8rpx;
	  padding: 6rpx 6rpx;
	}
	 
	.tab-text {
	  text-align: left;
	  overflow: hidden;
	  text-overflow: ellipsis;
	  white-space: nowrap;
	}
	 
	.close-btn {
	  background-color: transparent;
	  border: none;
	  font-size: 32rpx;
	  color: #5E6D82;
	  cursor: pointer;
	  margin: 0rpx 0rpx 4rpx 10rpx;
	}

	.example {
		padding: 30rpx;
		background-color: #fff;
	}

	.segmented-control {
		margin-bottom: 30rpx;
	}

	.button-group {
		margin-top: 30rpx;
		display: flex;
		justify-content: space-around;
	}

	.form-item {
		display: flex;
		align-items: center;
		flex: 1;
	}

	.button {
		display: flex;
		align-items: center;
		height: 70rpx;
		line-height: 70rpx;
		margin-left: 20rpx;
	}
	
	.page-body {
		height: calc(100vh - var(--window-top) - var(--status-bar-height));
	}
	
	.wrapper {
		height: 100%;
	}
	
	.editor-wrapper {
		height: calc(100vh - var(--window-top) - var(--status-bar-height) - 160rpx - 92rpx);
		background: #fff;
	}
	
	.iconfont {
		display: inline-block;
		padding: 16rpx 16rpx;
		width: 48rpx;
		height: 48rpx;
		cursor: pointer;
		font-size: 40rpx;
	}
	
	.toolbar {
		box-sizing: border-box;
		border-bottom: 0;
		font-family: 'Helvetica Neue', 'Helvetica', 'Arial', sans-serif;
	}
	
	.ql-container {
		box-sizing: border-box;
		padding: 24rpx 30rpx;
		width: 100%;
		min-height: 30vh;
		height: 100%;
		/* margin-top: 40rpx; */
		font-size: 32rpx;
		line-height: 1.5;
	}
	
	.ql-active {
		color: #06c;
	}
</style>
